package com.cskaoyan.service.wx_catalog_service;

import com.cskaoyan.bean.Category;
import com.cskaoyan.bean.CategoryExample;
import com.cskaoyan.bean.wx_vo.catalog.BaseWxCatalogVO;
import com.cskaoyan.bean.wx_vo.catalog.CurrentWxCatalogVO;
import com.cskaoyan.bean.wx_vo.catalog.IndexWxCatalogVO;
import com.cskaoyan.converter.WxCatalogPOJO2VOConverter;
import com.cskaoyan.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description：
 * @author: 曹旭
 * @date: 2022/5/9 17:26
 */
@Service
public class WxCatalogServiceImpl implements WxCatalogService{
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    WxCatalogPOJO2VOConverter converter;

    @Override
    public IndexWxCatalogVO index() {
        // 先查出所有pid=0的目录,即父目录
        CategoryExample example = new CategoryExample();
        example.createCriteria().andPidEqualTo(0);
        List<Category> categories = this.categoryMapper.selectByExample(example);
        // POJO转VO
        ArrayList<BaseWxCatalogVO> categoryList = new ArrayList();
        for (Category category : categories) {
            categoryList.add(this.converter.convert(category));
        }
        // 用第一个元素当currentCategory
        BaseWxCatalogVO currentCategory = categoryList.get(0);

        //再去查currentSubCategory,直接调用current()方法
        List<BaseWxCatalogVO> currentSubCategory = this.current(currentCategory.getId()).getCurrentSubCategory();

        // 封装最终的结果

        IndexWxCatalogVO indexWxCatalogVO = IndexWxCatalogVO.builder().categoryList(categoryList)
                .currentCategory(currentCategory).currentSubCategory(currentSubCategory).build();
        return indexWxCatalogVO;
    }

    @Override
    public CurrentWxCatalogVO current(Integer id) {
        Category category = this.categoryMapper.selectByPrimaryKey(id);
        CategoryExample example = new CategoryExample();
        example.createCriteria().andPidEqualTo(id);
        List<Category> subMarketCategories = this.categoryMapper.selectByExample(example);
        // POJO转VO
        BaseWxCatalogVO baseWxCatalogVO = this.converter.convert(category);
        ArrayList<BaseWxCatalogVO> baseWxCatalogVOS = new ArrayList<>();
        for (Category subMarketCategory : subMarketCategories) {
            BaseWxCatalogVO subBaseWxCatalogVO = this.converter.convert(subMarketCategory);
            baseWxCatalogVOS.add(subBaseWxCatalogVO);
        }
        CurrentWxCatalogVO currentWxCatalogVO = CurrentWxCatalogVO.builder()
                .currentCategory(baseWxCatalogVO).currentSubCategory(baseWxCatalogVOS).build();
        return currentWxCatalogVO;
    }
}
